package com;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class AreaRunTime {
    private static final String sql = "INSERT  INTO sys_area(`code`,`name`,father_code,`type`) VALUES({0},{1},{2},{3});";

    public static void main(String[] args) throws IOException {

        String json = FileUtils.readFileToString(new File("area_mini.json"), "UTF-8");
        JSONArray jsonArray = JSONArray.parseArray(json);

        List<String> sqls = chooseJsonArray(jsonArray, 1, "86");
        sqls.stream().forEach(System.out::println);


    }

    private static List<String> chooseJsonArray(JSONArray jsonArray, Integer type, String fatherCode) {
        List<String> sqls = new ArrayList<>();
        jsonArray.stream().forEach(obj -> {
            JSONObject jsonObj = (JSONObject) obj;


            String sql = chooseJsonObj((JSONObject) jsonObj, type, fatherCode);
            sqls.add(sql);
            Object childrenObj = jsonObj.get("children");
            if (Objects.nonNull(childrenObj)) {
                String code = jsonObj.getString("value");
                JSONArray child = (JSONArray) childrenObj;
                List<String> childrenSQL = chooseJsonArray(child, type + 1, code);
                sqls.addAll(childrenSQL);
            }
        });

        return sqls;
    }

    private static String chooseJsonObj(JSONObject jsonObject, Integer type, String fatherCode) {
        String label = "'" + jsonObject.getString("label") + "'";
        String code = "'" + jsonObject.getString("value") + "'";

        return  MessageFormat.format(sql, code, label, "'" + fatherCode + "'", type);
    }
}
